<template>
    <div id="User">
        <el-row>
            <el-col :span="3"><el-button type="primary" @click="saveUserVisible = true">新增用户</el-button></el-col>
        </el-row>
        <el-card>
            <el-row>
                <el-col>
                    <el-table
                        :data="userList"
                        border
                        style="width: 100%"
                        max-height="800px">
                        <el-table-column
                        fixed
                        width="100"
                        prop="userName"
                        label="用户名称">
                        </el-table-column>
                        <el-table-column
                        prop="loginName"
                        label="登录名称">
                        </el-table-column>
                        <el-table-column
                        prop="sex"
                        label="性别">
                        <template slot-scope="scope">
                            <span v-show="scope.row.sex==0">女</span>
                            <span v-show="scope.row.sex==1">男</span>
                        </template> 
                        </el-table-column>
                        <el-table-column
                        prop="birthday"
                        label="出生日期">
                        </el-table-column>
                        <el-table-column
                        prop="avatarId"
                        label="头像"
                        width="100">
                        <template slot-scope="scope">
                           <img :src='`http://127.0.0.1:8082/getImageById?id=${scope.row.avatarId}`'  style="width:70px;height:70px;">
                        </template>
                        </el-table-column>
                        <el-table-column
                            fixed="right"
                            label="操作"
                            width="230">
                            <template slot-scope="scope">
                                <el-button @click="userView(scope.row)" type="success" size="small">详情</el-button>
                                <el-button @click="userEdit(scope.row)" type="primary" size="small">修改</el-button>
                                <el-button @click="hintDetele(scope.row.id)" type="danger" size="small">删除</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column
                            fixed="right"
                            label="绑定操作"
                            width="300">
                            <template slot-scope="scope">
                                <el-button @click="userEditMail(scope.row)" type="info" plain size="small">绑定/更改邮箱号</el-button>
                                <el-button @click="userEditPhone(scope.row)" type="info" plain size="small">绑定/更改手机号</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <!-- 分页组件 -->
            <div class='block'>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage4"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="page.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.total"
                >
                </el-pagination>
            </div>
        </el-card>
        <!-- 新增用户弹窗 -->
        <el-dialog
            title="新增用户"
            :visible.sync="saveUserVisible"
            width="30%"
            :before-close="handleClose"
            :destroy-on-close="true">
            <el-form :model="userForm" :rules="saveUserRules" ref="userForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名称" prop="userName">
                    <el-input v-model="userForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="登录名" prop="loginName">
                    <el-input v-model="userForm.loginName"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="userForm.password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input v-model="userForm.checkPass"></el-input>
                </el-form-item>
                <el-form-item label="邮箱号" prop="mail">
                    <el-input placeholder="您的邮箱号" v-model="userForm.mail" clearable style="width:80%"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                    <el-input placeholder="输入验证码" v-model="userForm.code" clearable style="width:46%"></el-input>
                    <el-button class="login_button" :class="{disabled: !this.canClick}" style="margin-left:14px" @click="saveCountDown('userForm')">{{content}}</el-button>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthday">
                    <el-date-picker type="date" placeholder="选择日期" v-model="userForm.birthday"></el-date-picker>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="userForm.sex" size="medium">
                        <el-radio border label="1">男</el-radio>
                        <el-radio border label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="头像" >
                    <el-upload
                        class="avatar-uploader"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="saveSubmitForm('userForm')">立即创建</el-button>
                    <el-button @click="resetForm('userForm')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 修改用户弹窗 -->
        <el-dialog
            title="修改用户"
            :visible.sync="editUserVisible"
            width="30%"
            :destroy-on-close="true">
            <el-form :model="userFormEdit" :rules="editUserRules" ref="userFormEdit" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名称" prop="userName">
                    <el-input v-model="userFormEdit.userName"></el-input>
                </el-form-item>
                <el-form-item label="登录名" prop="loginName">
                    <el-input v-model="userFormEdit.loginName"></el-input>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthday">
                    <el-date-picker type="date" placeholder="选择日期" v-model="userFormEdit.birthday"></el-date-picker>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="userFormEdit.sex" size="medium">
                        <el-radio border :label="1">男</el-radio>
                        <el-radio border :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="头像" >
                    <el-upload
                        class="avatar-uploader"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="editSubmitForm('userFormEdit')">立即修改</el-button>
                    <el-button @click="resetForm('userFormEdit')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 查看详情用户弹窗 -->
        <el-dialog
            title="查看详情"
            :visible.sync="viewUserVisible"
            width="30%"
            :destroy-on-close="true">
            <el-form :model="userFormView" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名称" prop="userName">
                    <el-input v-model="userFormView.userName" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="登录名" prop="loginName">
                    <el-input v-model="userFormView.loginName" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱号" prop="mail">
                    <el-input v-model="userFormView.mail" clearable style="width:80%" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="userFormView.phone" clearable style="width:80%" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthday">
                    <el-date-picker type="date" placeholder="选择日期" v-model="userFormView.birthday" :disabled="true"></el-date-picker>
                </el-form-item>
                 <el-form-item label="性别" prop="sex">
                    <el-radio-group disabled v-model="userFormView.sex" size="medium">
                        <el-radio border :label="1">男</el-radio>
                        <el-radio border :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="头像" >
                    <img v-if="imageUrlView" :src="imageUrlView" class="avatar">
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 邮箱更换绑定弹窗 -->
        <el-dialog
            title="邮箱更改绑定"
            :visible.sync="editUserMailVisible"
            width="30%"
            :destroy-on-close="true">
            <el-form :model="userFormEdit" :rules="editUserRules" ref="userFormEdit" label-width="100px" class="demo-ruleForm">
                <el-form-item label="邮箱号" prop="mail">
                    <el-input placeholder="您的邮箱号" v-model="userFormEdit.mail" clearable style="width:80%"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                    <el-input placeholder="输入验证码" v-model="userFormEdit.code" clearable style="width:46%"></el-input>
                    <el-button class="login_button" :class="{disabled: !this.canClick}" style="margin-left:14px" @click="editSendCodeByQQMailRe('userFormEdit')">{{content}}</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="editUserMailSubmit('userFormEdit')">立即修改</el-button>
                    <el-button @click="resetForm('userFormEdit')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 手机号更换绑定弹窗 -->
        <el-dialog
            title="手机号更改绑定"
            :visible.sync="editUserPhoneVisible"
            width="30%"
            :destroy-on-close="true">
            <el-form :model="userFormEdit" :rules="editUserRules" ref="userFormEdit" label-width="100px" class="demo-ruleForm">
                <el-form-item label="手机号" prop="mail">
                    <el-input placeholder="您的手机号" v-model="userForm.phone" clearable style="width:80%"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                    <el-input placeholder="输入验证码" v-model="userForm.code" clearable style="width:46%"></el-input>
                    <el-button class="login_button" :class="{disabled: !this.canClick}" style="margin-left:14px" @click="countDownPhone('userForm')">{{content}}</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="editSubmitForm('userFormEdit')">立即修改</el-button>
                    <el-button @click="resetForm('userFormEdit')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'UserViews',
    data () {
        // 邮箱校验是否绑定
        var validateMailQQ = (rule, value, callback) => {
            let reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if (value === '') {
                callback(new Error('邮箱不能为空'));
            } else if (!reg.test(value)) {
                callback(new Error('输入正确的邮箱'))
            } else {
                this.$axios.get('http://127.0.0.1:8082/login/checkMail?mail=' + value).then(res => {
                    if (res.data.code === '999') {
                        callback(new Error('当前邮箱已绑定用户'))
                    } else {
                        callback();
                    }
                })
            }
        }
        // 邮箱校验是否绑定(绑定/更改绑定邮箱校验)
        var validateMailQQEdit = (rule, value, callback) => {
            let reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if (value === '') {
                callback(new Error('邮箱不能为空'));
            } else if (!reg.test(value)) {
                callback(new Error('输入正确的邮箱'))
            } else {
                this.$axios.get('http://127.0.0.1:8082/user/checkMailEdit',{
                    params: {
                        mail: value,
                        id: this.userFormEdit.id
                    }
                }).then(res => {
                    if (res.data.code === '999') {
                        callback(new Error('当前邮箱已绑定用户'))
                    } else {
                        callback();
                    }
                })
            }
        }
        // 验证方法
        let validatorPhone = function (phone, value, callback) {
            //验证手机号的正则表达式
            let reg=/^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/
            if (value !== '') {
                if (!reg.test(value)) {
                    callback(new Error('输入正确手机号'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        }
        // 校验密码
        var checkAge = (rule, value, callback) => {
            if (value !== '') {
                if (value.length < 6) {
                    callback(new Error('长度在 6 个字符'))
                    this.$axios.get('http://127.0.0.1:8082/user/checkLoginName?loginName=', + value).then(res => {
                        if(res > 0){
                            callback(new Error('当前名字已存在'))
                        } else {
                            callback();
                        }
                    })
                } else {
                    callback()
                }
            } else if (value === '') {
                callback(new Error('请输入密码'))
            } else {
                callback()
            }
        }
        // 再次输入密码校验规则
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.userForm.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        // 校验登录名查重
        var checkLoginName = (rule, value, callback) => {
            var reg = /^[A-Za-z]+$/
            console.log(value.length)
            if (value == '') {
                callback(new Error('登录名不能为空'))
            } else if (!reg.test(value) || value.length <= 6){
                callback(new Error('6个字符以上的纯英文组成'))
            } else {
                this.$axios.get('http://127.0.0.1:8082/user/checkLoginName?loginName=' + value).then(res => {
                    if(res.data.obj > 0){
                        callback(new Error('当前名字已存在'))
                    } else {
                        callback();
                    }
                })
            }
        }
        // 修改校验登录名查重
        var editCheckLoginName = (rule, value, callback) => {
            var reg = /^[A-Za-z]+$/
            if (value == '') {
                callback(new Error('登录名不能为空'))
            } else if (!reg.test(value) || value.length <= 6){
                callback(new Error('6个字符以上的纯英文组成'))
            } else if (value == this.loginNameRule){
                callback()
            } else {
                this.$axios.get('http://127.0.0.1:8082/user/checkLoginName?loginName=' + value).then(res => {
                    if(res.data.obj > 0){
                        callback(new Error('当前名字已存在'))
                    } else {
                        callback()
                    }
                })
            }
        }
        // 再次输入密码校验规则
        var editValidatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.userFormEdit.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        return {
            // 用于校验登录名存放使用
            loginNameRule: '',
            // 更改手机号绑定弹窗状态
            editUserPhoneVisible: false,
            // 更改邮箱绑定弹窗状态
            editUserMailVisible: false,
            // 用户修改弹窗状态
            editUserVisible: false,
            // 用户新增弹窗状态
            saveUserVisible: false,
            // 用户查看详情弹窗状态
            viewUserVisible: false,
            // 存储用户集合
            userList: [],
            // 用户对象
            userForm: {
                id: '',
                userName: '', // 用户名称
                loginName: '', // 登录名称
                password: '', // 密码
                birthday: '', // 生日
                sex: '', // 性别
                cardId: '', // 会员卡类型
                cardExpireTime: '', // 会员卡到期时间
                createTime: '', // 注册时间
                updateTime: '', // 修改时间
                checkPass: '', // 校验密码
                phone: '', //手机号
                // 邮箱号
                mail: ''
            },
            // 查看用户对象
            userFormView: {
                id: '',
                userName: '', // 用户名称
                loginName: '', // 登录名称
                password: '', // 密码
                birthday: '', // 生日
                sex: '', // 性别
                cardId: '', // 会员卡类型
                cardExpireTime: '', // 会员卡到期时间
                createTime: '', // 注册时间
                updateTime: '', // 修改时间
                checkPass: '', // 校验密码
                phone: '', //手机号
                // 邮箱号
                mail: ''
            },
            // 修改用户对象
            userFormEdit: {
                id: '',
                userName: '', // 用户名称
                loginName: '', // 登录名称
                password: '', // 密码
                birthday: '', // 生日
                sex: '', // 性别
                cardId: '', // 会员卡类型
                cardExpireTime: '', // 会员卡到期时间
                createTime: '', // 注册时间
                updateTime: '', // 修改时间
                checkPass: '', // 校验密码
                avatarId: '',
                phone: '', //手机号
                // 邮箱号
                mail: ''
            },
            // 用户新增校验
            saveUserRules: {
                userName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 3, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                loginName: [
                    { validator: checkLoginName, trigger: 'blur' }
                ],
                password: [
                    { validator: checkAge, trigger: 'blur' }
                ],
                checkPass: [
                    { validator: validatePass, trigger: 'blur' }
                ],
                birthday: [
                    { required: true, message: '请选择生日', trigger: 'change' },
                ],
                phone: [
                    { validator: validatorPhone, trigger: 'blur' }
                ],
                mail: [
                    { validator: validateMailQQ , trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                ],
            },
            // 用户修改校验
            editUserRules: {
                userName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 3, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                loginName: [
                    { validator: editCheckLoginName, trigger: 'blur' }
                ],
                checkPass: [
                    { validator: editValidatePass, trigger: 'blur' }
                ],
                birthday: [
                    { required: true, message: '请选择生日', trigger: 'change' },
                ],
                phone: [
                    { validator: validatorPhone, trigger: 'blur' }
                ],
                mail: [
                    { validator: validateMailQQEdit , trigger: 'blur' }
                ],
            },
            // 图片
            imageUrl: '',
            imageUrlView: '',
            imageUrlEdit: '',
            // 图片对象
			imageFile: File,
            // 分页对象
			page: {
				// 每页条数
				pageSize: 10,
				// 分页页数
				pageNum: 1,
				// 分页总条数
				total: 0
			},
            // 分页默认页数
            currentPage4: 1,
            // 
            loginName: '',
            // 记录具体倒计时时间
            totalTime: 120,
            // 按钮里显示的内容
            content: '发送验证',
            // 添加canClick
			canClick: true,
        }
    },
    mounted () {
        // 初始化渲染用户列表
        this.getUserList()
    },
    methods: {
        // 绑定/更换邮箱提交校验判断
        editUserMailSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.editMail()
                } else {
                    return false;
                }
            })
        },
        // 绑定/更换用户邮箱
        editMail () {
            this.$axios.get('http://127.0.0.1:8082/user/editMail',{
                params: {
                    mail: this.userFormEdit.mail,
                    id: this.userFormEdit.id,
                    code: this.userFormEdit.code
                   }
            }).then(res => {
                if (res.data.obj > 0){
                    this.editUserMailVisible = false
                    this.message('绑定成功', 'success')
                } else {
                    this.message('绑定失败, 验证码不正确', 'warning')
                }
            })
        },
        // 绑定更改/邮箱发送验证码
        editSendCodeByQQMailRe () {
            this.$axios.get('http://127.0.0.1:8082/login/sendCodeByQQMailRe?mail=' + this.userFormEdit.mail)
            .then(res => {
                if (res.data.code === '999') {
                    this.totalTime = 0
                    this.message('邮箱未绑定', 'warning')
                }
            })
        },
        // 新增邮箱发送验证码
        saveSendCodeByQQMailRe () {
            this.$axios.get('http://127.0.0.1:8082/login/sendCodeByQQMailRe?mail=' + this.userForm.mail)
            .then(res => {
                if (res.data.code === '999') {
                    this.totalTime = 0
                    this.message('邮箱未绑定', 'warning')
                }
            })
        },
        // 点击发送验证码时倒计时
        saveCountDown (userForm) {
            this.$refs[userForm].validateField('mail', (valid) => {
                if (valid === '') {
                    this.saveSendCodeByQQMailRe()
                    if (!this.canClick) return  //改动的是这两行代码
                        this.canClick = false
                        this.content = this.totalTime + 's后重新发送'
                        let clock = window.setInterval(() => {
                        this.totalTime--
                        this.content = this.totalTime + 's后重新发送'
                    if (this.totalTime < 0) {
                        window.clearInterval(clock)
                        this.content = '重新发送验证码'
                        this.totalTime = 120
                        this.canClick = true  //这里重新开启
                    }
                    },1000)
                } else {
                    return false;
                }
            })
        },
        // 点击发送验证码时倒计时
        editCountDown (userForm) {
            this.$refs[userForm].validateField('mail', (valid) => {
                if (valid === '') {
                    this.editSendCodeByQQMailRe()
                    if (!this.canClick) return  //改动的是这两行代码
                        this.canClick = false
                        this.content = this.totalTime + 's后重新发送'
                        let clock = window.setInterval(() => {
                        this.totalTime--
                        this.content = this.totalTime + 's后重新发送'
                    if (this.totalTime < 0) {
                        window.clearInterval(clock)
                        this.content = '重新发送验证码'
                        this.totalTime = 120
                        this.canClick = true  //这里重新开启
                    }
                    },1000)
                } else {
                    return false;
                }
            })
        },
        // 删除提示框
        hintDetele (id) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteUser(id)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        deleteUser (id) {
            this.$axios.delete('http://127.0.0.1:8082/user/deleteUser?id=' + id).then(res =>{
                if (res.data.obj > 0) {
                    this.message('恭喜您，删除成功', 'success')
                    this.getUserList()
                } else {
                    this.message('删除失败', 'warning')
                }
            })
        },
        // 分页pageSize 改变时会触发方法
		handleSizeChange (ps) {
			this.page.pageSize = ps
			this.getUserList()
		},
        // 分页currentPage 改变时会触发方法
		handleCurrentChange (pn) {
			this.page.pageNum = pn
			this.getUserList()
		},
        // 获取用户集合
        getUserList () {
            this.$axios.get('http://127.0.0.1:8082/user/getUserList', {
                params: {
                    pageSize: this.page.pageSize,
                    pageNum: this.page.pageNum
                }
            }).then(res => {
                this.userList = res.data.obj.content
                this.page.total = res.data.obj.total
            }).catch(error => {
                this.$message.error('服务器崩溃了，请稍后再尝试使用！');
            })
        },
        // 用户新增方法
        saveUser () {
			var formdata = new FormData()
            formdata.set('userName', this.userForm.userName)
            formdata.set('password', this.userForm.password)
            formdata.set('loginName', this.userForm.loginName)
            formdata.set('sex', this.userForm.sex)
            formdata.set('birthday', this.userForm.birthday)
            formdata.set('phone', this.userForm.phone)
            formdata.set('mail', this.userForm.mail)
			if (this.imageFile.name !== 'File') {
				formdata.set('file', this.imageFile, this.imageFile.name)
			}
            this.$axios.post('http://127.0.0.1:8082/user/saveUser', formdata).then(res => {
                if (res.data.obj > 0) {
                    this.message('恭喜您，添加成功', 'success')
                    this.saveUserVisible = false
                    this.imageUrl = ''
                    this.imageFile = File
                    this.userForm = {
                        id: '',
                        userName: '', // 用户名称
                        loginName: '', // 登录名称
                        password: '', // 密码
                        birthday: '', // 生日
                        sex: '', // 性别
                        cardId: '', // 会员卡类型
                        cardExpireTime: '', // 会员卡到期时间
                        createTime: '', // 注册时间
                        updateTime: '', // 修改时间
                        checkPass: '' // 校验密码
                    }
                    this.getUserList()
                } else {
					this.message('添加失败', 'warning')
                }
            }).catch(error => {
                this.$message.error('服务器崩溃了，请稍后再尝试使用！');
            })
        },
        handleAvatarSuccess (res, file) {
			this.imageUrl = URL.createObjectURL(file.raw)
		},
        // 上传图片图片校验
		beforeAvatarUpload (file) {
			const isJPG = file.type === 'image/jpeg'
			const isPNG = file.type === 'image/png'
			const isLt2M = file.size / 1024 / 1024 < 2
			if (!isJPG && !isPNG) {
				this.$message.error('上传头像图片只能是 JPG 和 PNG 格式!')
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!')
			}
			this.imageUrl = URL.createObjectURL(file)
			this.imageFile = file
			return false
		},
        // 弹窗关闭前的提醒
        handleClose(done) {
            this.$confirm('关闭后数据将不会被保存，确认关闭？')
            .then(_ => {
                done();
                // 用户对象
                this.userForm= {
                    id: '',
                    userName: '', // 用户名称
                    loginName: '', // 登录名称
                    password: '', // 密码
                    age: '', // 年龄
                    sex: '', // 性别
                    cardId: '', // 会员卡类型
                    cardExpireTime: '', // 会员卡到期时间
                    createTime: '', // 注册时间
                    updateTime: '', // 修改时间
                    checkPass: '' // 校验密码
                },
                this.imageUrl = ''
            })
            .catch(_ => {});
        },
        // 修改用户弹窗关闭前的提醒
        handleCloseEdit(done) {
            this.$confirm('关闭后数据将不会被保存，确认关闭？')
            .then(_ => {
                done();
                // 用户对象
                this.userFormEdit = {
                    id: '',
                    userName: '', // 用户名称
                    loginName: '', // 登录名称
                    password: '', // 密码
                    age: '', // 年龄
                    sex: '', // 性别
                    cardId: '', // 会员卡类型
                    cardExpireTime: '', // 会员卡到期时间
                    createTime: '', // 注册时间
                    updateTime: '', // 修改时间
                    checkPass: '', // 校验密码
                    // 邮箱号
                    mail: '',
                    // 手机号
                    phone: '' 
                }
            })
            .catch(_ => {});
        },
        // 打开user查看详情的弹框
        userView(row) {
            this.viewUserVisible = true
            this.userFormView = row
            this.imageUrlView = 'http://127.0.0.1:8082/getImageById?id=' + this.userFormView.avatarId
        },
        // 打开user修改的弹框
        userEdit(row) {
            this.editUserVisible = true
            this.userFormEdit = row
            this.loginNameRule = row.loginName
            this.$set(this.userFormEdit, 'checkPass', '')
            this.imageUrl = 'http://127.0.0.1:8082/getImageById?id=' + this.userFormEdit.avatarId
        },
        // 打开user更改邮箱绑定的弹框
        userEditMail(row) {
            this.editUserMailVisible = true
            this.userFormEdit = row
        },
        // 打开user更改手机号绑定的弹框
        userEditPhone(row) {
            this.editUserPhoneVisible = true
            this.userFormEdit = row
        },
        // 创建用户提交校验判断
        saveSubmitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.saveUser()
                } else {
                    return false;
                }
            })
        },
        // 创建用户提交校验判断
        editSubmitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.editUser()
                } else {
                    return false;
                }
            })
        },
        // 修改用户信息
        editUser () {
            this.$set(this.userFormEdit, 'birthday', Date.parse(this.userFormEdit.birthday))
            this.userFormEdit.birthday = this.StrToGMT(this.userFormEdit.birthday)
            var formdata = new FormData()
            formdata.set('id', this.userFormEdit.id)
            formdata.set('userName', this.userFormEdit.userName)
            formdata.set('loginName', this.userFormEdit.loginName)
            formdata.set('sex', this.userFormEdit.sex)
            formdata.set('birthday', this.userFormEdit.birthday)
            formdata.set('avartarId', this.userFormEdit.avatarId)
            formdata.set('phone', this.userFormEdit.phone)
			if (this.imageFile.name !== 'File') {
				formdata.set('file', this.imageFile, this.imageFile.name)
			}
            this.$axios.put('http://127.0.0.1:8082/user/editUser', formdata).then(res => {
                if (res.data.obj > 0) {
                    this.message('恭喜您，修改成功', 'success')
                    this.editUserVisible = false
                    this.imageUrl = ''
                    this.imageFile = File
                    this.userFormEdit = {
                        id: '',
                        userName: '', // 用户名称
                        loginName: '', // 登录名称
                        password: '', // 密码
                        birthday: '', // 生日
                        sex: '', // 性别
                        cardId: '', // 会员卡类型
                        cardExpireTime: '', // 会员卡到期时间
                        createTime: '', // 注册时间
                        updateTime: '', // 修改时间
                        checkPass: '' // 校验密码
                    }
                    this.getUserList()
                } else {
					this.message('修改失败', 'warning')
                }
            }).catch(error => {
                this.$message.error('服务器崩溃了，请稍后再尝试使用！');
            })
        },
        // 新增重置表单
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.imageUrl = ''
        },
        //消息提示框
        message(message,type){
            this.$message({
                message:message,
                type: type
            });
        },
        StrToGMT(time) {
            let GMT = new Date(time);
            return GMT;
        },
    }
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.el-icon-plus:before{
    line-height: 178px;
}
.block {
    text-align: center;
}
</style>
